package com.kc.gb.device.common.utils;

import com.kc.gb.device.common.dto.I18NException;
import com.kc.gb.device.common.enums.ErrorCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public class I18NHelper {

    public static String I18N_BASE_NAME = "i18n/messages";
    public static Locale I18N_DEFAULT_LOCALE = null;

    public static MessageSource getMessageSource() {
        return SpringHelper.getBean(MessageSource.class);
    }

    public static void setDefaultLocale(Locale locale) {
        LocaleContextHolder.setLocale(locale);
        LocaleContextHolder.setDefaultLocale(locale);
        I18N_DEFAULT_LOCALE = locale;
    }

    public static Locale getDefaultLocale() {
        return I18N_DEFAULT_LOCALE;
    }

    /**
     * 获取所有消息代码（通过反射，仅适用于 ResourceBundleMessageSource）
     */
    public static Set<String> getI18NCodes() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Set<String> keys = new HashSet<>();
        // 检查是否为 ResourceBundleMessageSource
        MessageSource messageSource = getMessageSource();
        if(!(messageSource instanceof ResourceBundleMessageSource)){
            throw new I18NException(ErrorCode.I18N_ERROR,"");
        }

        ResourceBundleMessageSource rbms = (ResourceBundleMessageSource) messageSource;
        Method getResourceBundle = null;
        Method[] methods = ResourceBundleMessageSource.class.getDeclaredMethods();
        for (Method method : methods) {
            String name = method.getName();
            if(StringUtils.containsIgnoreCase(name,"doGetBundle")){
                getResourceBundle = method;
                break;
            }
        }
        getResourceBundle.setAccessible(true);
        Locale defaultLocale = LocaleContextHolder.getLocale();
        String baseName =I18N_BASE_NAME;
        ResourceBundle resourceBundle = (ResourceBundle) getResourceBundle.invoke(rbms,baseName,defaultLocale);
        Enumeration<String> bundleKeys = resourceBundle.getKeys();
        while (bundleKeys.hasMoreElements()) {
            keys.add(bundleKeys.nextElement());
        }
        return keys;
    }

    public static Map<String,String> getI18NMap(Locale locale) throws NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        Map<String,String> values = new HashMap<>();
        Set<String> keys = getI18NCodes();
        MessageSource messageSource = getMessageSource();
        for (String key : keys) {
            values.put(key, messageSource.getMessage(key, null, locale));
        }
        return values;
    }

    /**
     * 获取特定语言的消息
     */
    public static String getLocaleMessage(Locale locale, String code, Object... args) {
        MessageSource messageSource = getMessageSource();
        return messageSource.getMessage(code, args, locale);
    }

    public static String getLocaleMessage(String code, Object... args) {
        Locale locale = I18NHelper.getDefaultLocale();
        if(locale == null){
            locale = LocaleContextHolder.getLocale();
        }
        MessageSource messageSource = getMessageSource();
        return messageSource.getMessage(code, args, locale);
    }
}
